package com.zhang.zhangapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.github.yoojia.fireeye.FireEye;
import com.github.yoojia.fireeye.Form;
import com.github.yoojia.fireeye.MessageDisplay;
import com.github.yoojia.fireeye.Result;
import com.github.yoojia.fireeye.StaticPattern;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.Constant;
import com.zhang.zhangapp.base.config.BaseConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.TokenData;
import com.zhang.zhangapp.bean.user.Message;
import com.zhang.zhangapp.bean.user.User;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.CreateMD5;
import com.zhang.zhangapp.utils.RSA;
import com.zhang.zhangapp.utils.SPUtils;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.view.mine.ThirdLoginSetMobail;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by 罗肖 on 2017/6/30.
 */


@ContentView(R.layout.activtity_login)
public class LoginActivity extends BaseAppCompatActivityActivity {
    private final static int ALI_LOGIN = 1000;
    /**
     * 确定登录
     */
    @ViewInject(R.id.login_sure)
    TextView sureText;

    @ViewInject(R.id.login_password_text)
    EditText passwordText;
    @ViewInject(R.id.login_phone_text)
    EditText phoneText;

    @ViewInject(R.id.shift_login_type)
    TextView shiftLoginTypeText;

    @ViewInject(R.id.get_code)
    TextView getCodeText;// 获取短信验证码

    @ViewInject(R.id.login_layout)
    LinearLayout loginLayout;

    private boolean loginByPassword = false;

    private User user;

    private TimeCount time;

    private IWXAPI iwxapi;

    private String thirdType;
    private String thirdCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        thirdCode = getIntent().getStringExtra("thirdCode");
        thirdType = getIntent().getStringExtra("thirdType");
        x.view().inject(this);
        initView();
        time = new TimeCount(60000, 1000);
        if (thirdCode != null && !thirdCode.equals(""))
            thirdLogin();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        thirdCode = intent.getStringExtra("thirdCode");
        thirdType = intent.getStringExtra("thirdType");
        thirdLogin();
    }

    private void initView() {
        phoneText.setSelection(phoneText.getText().toString().length());
        passwordText.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    private boolean checkForm(boolean isLogin) {
        MessageDisplay messageDisplay = new MessageDisplay() {

            @Override
            public void dismiss(TextView field) {
                field.setError(null);
            }

            @Override
            public void show(TextView field, String message) {
                field.setError(message);
                T.showShort(LoginActivity.this, message);
            }
        };

        Form form = new Form(loginLayout);
        FireEye fireEye = new FireEye(this);
        fireEye.add(phoneText, StaticPattern.Required, StaticPattern.Mobile);
        if (isLogin)
            fireEye.add(passwordText, StaticPattern.Required);
        Result result = fireEye.test();
        if (result.passed)
            return true;
        else return false;
    }

    /**
     * 登录
     */
    @Event(type = View.OnClickListener.class, value = R.id.login_sure)
    private void login(View view) {
        if (checkForm(true) && showLoadingDialog() && getCodeText.getVisibility() == View.VISIBLE) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("mobileNum", phoneText.getText().toString());
            params.put("smsCode", passwordText.getText().toString());
            CommonHttp.commonHttp("hzg/login/loginByCode", params, loginCallback);
        } else {
            Map<String, String> params = new HashMap<String, String>();
            params.put("mobileNum", phoneText.getText().toString());
            params.put("password", passwordText.getText().toString());
            CommonHttp.commonHttp("hzg/login/loginBySec", params, loginCallback);
        }
    }

    private void thirdLogin() {
        if (showLoadingDialog()) {

            Map<String, String> params = new HashMap<String, String>();
            params.put("thirdNum", thirdCode);
            params.put("type", thirdType);
            CommonHttp.commonHttp("/hzg/login/thirdLogin", params, loginCallback);
        }
    }

    /*
     切换登录方式
      */
    @Event(type = View.OnClickListener.class, value = R.id.shift_login_type)
    private void sthiftLoginType(View view) {
        loginByPassword = !loginByPassword;
        if (loginByPassword) {
            getCodeText.setVisibility(View.INVISIBLE);
            shiftLoginTypeText.setText("验证码登录");
            passwordText.setHint("密码");
            passwordText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        } else {
            getCodeText.setVisibility(View.VISIBLE);
            shiftLoginTypeText.setText("密码登录");
            passwordText.setHint("验证码");
            passwordText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }
    }

    /*
    获取短信验证码
     */
    @Event(type = View.OnClickListener.class, value = R.id.get_code)
    private void getCode(View view) {
        if (!checkForm(false)) {
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("mobileNum", phoneText.getText().toString());
        params.put("type", Constant.短信验证码登录);
        params.put("secretKey", CreateMD5.getMD5(phoneText.getText().toString() + Constant.短信验证码登录 + BaseConfig.SECRETKEY));
        CommonHttp.commonHttp("hzg/sms/sendCode", params, getCodeCallBack);
    }

    @Event(value = {R.id.wx_login, R.id.ali_login})
    private void thirdLogin(View view) {
        switch (view.getId()) {
            case R.id.wx_login:
                thirdType = "2";
                wxLogin();
                break;
            case R.id.ali_login:
                thirdType = "1";
                getAuthResultFormAuthInfo();
                break;
        }
    }


    /**
     * 微信登录
     */
    private void wxLogin() {
        iwxapi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        iwxapi.registerApp(Constant.WX_APP_ID);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        iwxapi.sendReq(req);
    }

    /**
     * 支付宝登录
     */
    private void getAuthResultFormAuthInfo() {
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String aliLoginStr = "apiname=com.alipay.account.auth&method=alipay.open.auth.sdk.code.get&app_id=2018041002529856&app_name=mc&" +
                        "biz_type=openservice&pid=2088031634641855&product_id=APP_FAST_LOGIN&scope=kuaijie&target_id=" + (new Date()).getTime() + "&auth_type=LOGIN&" +
                        "sign_type=RSA2";
                String sign = "";
                try {
                    sign = URLEncoder.encode(RSA.sign(aliLoginStr, BaseConfig.ALI_PRIVATE_KEY, "utf-8"), "utf-8");
                } catch (Exception e) {

                }
                AuthTask authTask = new AuthTask(LoginActivity.this);
                Map<String, String> result = authTask.authV2(aliLoginStr + "&sign=" + sign, true);
                android.os.Message message = new android.os.Message();
                message.what = ALI_LOGIN;
                message.obj = result;
                handler.sendMessage(message);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            if (msg.what == ALI_LOGIN) {
                AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                String resultStatus = authResult.getResultStatus();
                if ("9000".equals(resultStatus) && "200".equals(authResult.getResultCode())) {
                    thirdCode = authResult.getAuthCode();
                    thirdLogin();
                }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    MCallback getCodeCallBack = new MCallback() {
        @Override
        public void onSuccess(String data) {
            time.start();
        }

        @Override
        public void onSuccess(String message, String code) {
            T.showShort(LoginActivity.this, message);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            T.showShort(LoginActivity.this, ex.getMessage().toString());
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };

    /**
     * 登录回调
     */
    MCallback loginCallback = new MCallback() {
        @Override
        public void onSuccess(String data) {
            try {
                Gson gson = new Gson();
                TokenData tokenData = gson.fromJson(data, TokenData.class);
                if (tokenData != null) {
                    MApplication.getInstance().setUser(tokenData.getMember(), tokenData.getTokens(), tokenData.getTickets());
                    if ((Boolean) SPUtils.get(LoginActivity.this, SPUtils.IS_SAVE_LOGIN_INFO, false)) {
                        SPUtils.put(LoginActivity.this, SPUtils.USER_NAME, phoneText.getText().toString());
                        SPUtils.put(LoginActivity.this, SPUtils.PASSWORD, passwordText.getText().toString());
                    }
                    setResult(RESULT_OK);
                    LoginActivity.this.finish();
                }
            } catch (Exception e) {
                T.showShort(LoginActivity.this, "请求失败");
            }
        }

        @Override
        public void onSuccess(String message, String code) {
            if ("10".equals(code)) {
                Intent intent = new Intent(LoginActivity.this, ThirdLoginSetMobail.class);
                intent.putExtra("thirdNum", thirdCode);
                intent.putExtra("type", thirdType);
                startActivityForResult(intent, 1000);
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            dismisionDalog();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        time.cancel();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if (requestCode == 1000)
        this.finish();
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            getCodeText.setText("获取验证码");
            getCodeText.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            getCodeText.setEnabled(false);
            getCodeText.setText(millisUntilFinished / 1000 + "秒");
        }
    }

}
